<template>
  <!-- 关联运输工具组件 -->
  <div>

  <el-form
          ref="formData"
          :model="form"
          :rules="rules"
          label-width="138px"
          label-suffix=":"
          size="small"
          class="flex-form-4"
        >
          <el-form-item label="车牌号" prop="transportName">
           <el-input
            ref="vehicleInput"
            @focus="openSelectVehicle"
            v-model.trim="form.transportName"
            placeholder="请选择车辆"
          />
          </el-form-item>
          <el-form-item label="车辆位置" prop="location">
            <el-select v-model.trim="form.location" placeholder="请选择车辆位置">
              <el-option v-for="(item, index) in select_vehicle_location" :key="index"
                         :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="挂车车牌" prop="trayName">
            <el-input
              v-model="form.trayName"
              size="mini"
              placeholder="请输入挂车车牌"
            />
          </el-form-item>
          <el-form-item label="集装箱信息" prop="contaList">
            <el-button class="input-btn" icon="el-icon-plus" @click="handleConta">添加({{form.contaShowNum}})
            </el-button
            >
          </el-form-item>
  </el-form>

  <div slot="footer" class="dialog-footer">
    <el-button type="primary" plain icon="el-icon-delete" @click="resetVehicleForm()" size="small">重置</el-button>
    <el-button type="success" icon="el-icon-check" @click="submitForm()" size="small">确认</el-button>
  </div>



    <el-table :data="submitVehicleList" size="mini" style="width: 100%; margin-top: 15px;" border>
      <el-empty
        slot="empty"
        :image="require('@/assets/images/empty.png')"
        :image-size="80"
      ></el-empty>
      <el-table-column prop="transportId" label="车辆海关编码" align="center"></el-table-column>
      <el-table-column prop="transportName" label="车牌号" align="center"></el-table-column>
      <el-table-column prop="selfWt" label="自重" align="center"> </el-table-column>
      <el-table-column prop="location" label="车辆位置" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bill_vehicle_location" :value="scope.row.location"/>
        </template>
      </el-table-column>
      <el-table-column prop="icCard" label="IC卡" align="center"></el-table-column>
      <el-table-column prop="rfid" label="电子车牌" align="center"></el-table-column>
      <el-table-column prop="trayName" label="挂车" align="center"></el-table-column>
      <el-table-column prop="trayWeight" label="挂车重量" align="center"></el-table-column>
      <el-table-column prop="contaShow" label="集装箱" align="center"></el-table-column>
      <el-table-column fixed="right" label="操作" width="120" v-if="dialogType != 'detail'">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleClickEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click.native.prevent="deleteVehicleItem(scope.$index, submitVehicleList)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="submitVehicleList.length > 0"
      :small="true"
      :total="submitVehicleList.length"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />



    <vehicle-select ref="vehicleSel" @returnValue="selectVehicleResult"></vehicle-select>

    <!-- 集装箱信息 -->
    <container-info
      ref="containerInfo"
      @submitContainerInfo="submitContainerInfo"
      :vehicleContaList="itemVahicleContaList"
    ></container-info>

  </div>
</template>

<script>
import { findVehicleList } from "@/api/billsdecl/preVehicleRecord";
import VehicleSelect from "@/views/billsdecl/components/VehicleSelect";
import ContainerInfo from "@/views/billsdecl/components/containerInfo";
export default {
  dicts: ["bt_vehicle_type","bill_vehicle_location"],
  components: {
    VehicleSelect,ContainerInfo
  },
  props: {
    editVehicleData: {
      type: Array,
      default: () => []
    },
    editContaData: {
      type: Array,
      default: () => []
    },
    dialogType: {}
  },
  data() {
    return {
      tableData: [],
      //车辆序号默认从1开始
      curVehicleNo:1,
      selectedList: [],
      submitVehicleList: [],
      showDrawer: false,
      searchValue: "",
      //车辆位置选择
      select_vehicle_location:[{value:'0',label:'未进场'},{value:'1',label:'已进场'},{value:'2',label:'已出场'}],
      //车辆集装箱列表
      vahicleContaList:[],
      //单个车辆的集装箱列表
      itemVahicleContaList:[],
      //编辑索引
      editIndex: null,
      vehicleItemOpType:'add',

      queryParams: {
        pageNum: 1,
        pageSize: 10,
        plateNo: ""
      },
      total: 0,
      form: {
        id: null,
        platSeqNo: null,
        transportId: null,
        transportName: null,
        selfWt: 0,
        icCard: null,
        rfid: null,
        location: null,
        vehicleStatus: "0",
        trayName: null,
        trayWeight: 0,
        contaShow:null,
        contaShowNum:0
      },
      rules:{
        transportName: [
          {
            required: true,
            message: "车牌号不能为空",
            trigger: ["blur", "change"],
          },
        ],
        location: [
          {
            required: true,
            message: "车辆位置不能为空",
            trigger: ["blur", "change"],
          },
        ],
      }
    };
  },
  watch: {
    "editVehicleData": {
      immediate: true,
      handler(val) {
        if(val) {
          this.submitVehicleList = this.editVehicleData;
        }
      }
    },
    "editContaData": {
      immediate: true,
      handler(val) {
        if(val) {
          this.vahicleContaList = this.editContaData;
          if( this.vahicleContaList==null || this.vahicleContaList.length==0){
            return;
          }
           this.submitVehicleList.map(item=>{
            // let tempVehicleContaList=[];
             let tempVehicleContaList= this.vahicleContaList.filter(conta=>conta.transportId==item.transportId);
             if(tempVehicleContaList!=null&&tempVehicleContaList.length>0){
                item.contaShow=tempVehicleContaList.map(n=>n.contaNo).join(",")
             }
             return item;
           });
        }
      }
    }
  },
  methods: {

    resetVehicleForm(){
       this.$refs["formData"].resetFields();
       this.initVehicleForm();
    },
    //初始化表单，因为编辑过后某些字段没有清空
    initVehicleForm(){
      this.form.id=null;
      this.form.platSeqNo=null;
      this.form.transportId=null;
      this.form.transportName=null;
      this.form.selfWt=null;
      this.form.icCard=null;
      this.form.rfid=null;
      this.form.location=null;
      this.form.vehicleStatus=null;
      this.form.trayName=null;
      this.form.trayWeight=null;
      this.form.contaShow=null,
      this.form.contaShowNum=0;
    },

    handleAddVehicle() {
      this.selectedList = [];
      this.showDrawer = true;
      this.getList();
    },
    getList() {
      this.loading = true;
      listVehicle(this.queryParams)
        .then((resp) => {
          this.tableData = resp.rows;
          this.total = resp.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    submitForm(){
      this.$refs["formData"].validate(valid => {
        if (valid) {
           if (this.vehicleItemOpType == "edit") {
              console.log("更换的index:"+this.editIndex )
              this.submitVehicleList.splice(this.editIndex, 1, {
                ...this.form
              });
              this.addVehicleContaToList();
              this.vehicleItemOpType='add';
           }
            this.resetVehicleForm();
        }
      });
    },
    //提交编辑车辆的时候，再把车辆对应的集装箱列表加入到集装箱列表中去
    addVehicleContaToList(){
      if(this.itemVahicleContaList.length==0){
        return;
      }
      debugger;
      //删除之前存在的车辆集装箱
      this.vahicleContaList= this.vahicleContaList.filter(n=>this.form.transportId!=n.transportId);
      for (var i=0;i<this.itemVahicleContaList.length;i++){
        let vehicleConta={...this.itemVahicleContaList[i]};
        vehicleConta.transportId=this.form.transportId;
        vehicleConta.transportName=this.form.transportName;
        this.vahicleContaList.push(vehicleConta);
      }
      this.itemVahicleContaList=[];
    },


    //点击编辑
    handleClickEdit(index, row) {
         this.vehicleItemOpType='edit';
         this.editIndex = index;
         console.log("点击的index:"+this.editIndex )
      console.log(row);
      this.form = {...row};//JSON.parse(JSON.stringify(row));
      this.form.contaShowNum=this.vahicleContaList.filter(n=>row.transportId==n.transportId).length;
      console.log(this.form);
    },

    deleteVehicleItem(index, rows) {
      rows.splice(index, 1);
    },

     // 选择车辆
     openSelectVehicle() {
      this.$refs.vehicleSel.open();
      this.$refs.vehicleInput.blur();
    },
    selectVehicleResult(vehicleList) {
      console.log("返回来了");
      console.log(vehicleList);
      let $this=this;
      vehicleList.forEach(function(item,index,arr){
        let vehicleItem={};
        vehicleItem.transportId=item.veCustomsNo;
        vehicleItem.transportName=item.realVeNo;
        vehicleItem.selfWt=item.selfWt;
        vehicleItem.icCard=item.cardNo;
        vehicleItem.rfid=item.rfid;
        vehicleItem.location='0';
        vehicleItem.trayName='';
        vehicleItem.trayWeight=0;
        let existItem=$this.submitVehicleList.find(n=>n.transportName==item.realVeNo);
        if(!existItem){
          $this.submitVehicleList.push(vehicleItem);
        }
      })

    },
    deleteRow(index, rows) {
      this.submitVehicleList.splice(index, 1);
    },
    // 添加集装箱
    handleConta() {
      console.log(this.form);
      if(this.form.transportId==null||this.form.transportId.trim().length==0){
        this.$modal.msgWarning("请选择编辑要加集装箱的车辆");
        return;
      }
      //添加的时候把已有的集装箱反写回去
      this.itemVahicleContaList=this.vahicleContaList.filter(n=>this.form.transportId==n.transportId);
      this.$nextTick(() => {
        this.$refs.containerInfo.open();
      });

    },
    // 集装箱list
    submitContainerInfo(valArr) {
      if(valArr==null||valArr.length==0){
        return;
      }
      //先临时存在,点确定的时候再加入到
      this.itemVahicleContaList=[...valArr];
      this.form.contaShowNum=valArr.length;
      this.form.contaShow=valArr.map(n=>n.contaNo).join(",");
      valArr=null;
    },

  },
};
</script>

<style lang="scss" scoped>
.common-addBtn {
  margin-top: 15px;
}
.searchBox {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  ::v-deep .el-button--primary {
    padding: 5px 10px;
    border-radius: 5px;
  }
  .el-input {
    width: 200px;
    margin-right: 10px;
  }
}
::v-deep .el-empty {
  padding: 10px 0;
}
::v-deep .el-empty__description {
  margin-top: 0;
  p {
    font-size: 12px;
  }
}

.dialog-footer{
  text-align: center;
}
</style>
